package com.zcy.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 定义切点，拦截controller包下所有类的所有方法
    @Pointcut("execution(* com.zcy.controller..*(..))")
    public void controllerMethods() {
    }

    // 环绕通知
    @Around("controllerMethods()")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        // 获取方法信息
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        
        logger.info("开始执行 {}.{} 方法", className, methodName);
        
        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            
            logger.info("{}.{} 方法执行完成，耗时: {} ms", className, methodName, executionTime);
            
            return result;
        } catch (Exception e) {
            logger.error("{}.{} 方法执行出错: {}", className, methodName, e.getMessage());
            throw e;
        }
    }
}